//
//  GizWifiManager.m
//  O2Cat
//
//  Created by xiabin on 15/12/18.
//  Copyright © 2015年 QiDao.Purifier. All rights reserved.
//

#import "GizWifiManager.h"
#import <SystemConfiguration/CaptiveNetwork.h>

static GizWifiManager *sharedManager;
typedef enum {
    GetDeviceJobId = 1,
    BindDeviceJobId = 2,
} WifiJobId;

@implementation GizWifiManager

+(GizWifiManager*)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager=[[GizWifiManager alloc]init];
    });
    return sharedManager;
}

//初始化
-(void) initManager:(NSString*)appid AndProductKey:(NSString*)pk
{
    self.appid = appid;
    self.productkey = pk;
    [XPGWifiSDK startWithAppID:appid];
    // 设置日志分级、日志输出文件、是否打印二进制数据
    [XPGWifiSDK setLogLevel:XPGWifiLogLevelError logFile:@"logfile.txt" printDataLevel:YES];
    [XPGWifiSDK sharedInstance].delegate = self;
    [[XPGWifiSDK sharedInstance] userLoginWithUserName:@"xelight@163.com" password:@"12345asdfg"];
}


- (void)XPGWifiSDK:(XPGWifiSDK *)wifiSDK didUserLogin:(NSNumber *)error errorMessage:(NSString *)errorMessage uid:(NSString *)uid token:(NSString *)token
{
    // 登录成功，自动设置相关信息
    int nErr = [error intValue];
    NSLog(@"-----------------------> UserLogin result:%d", nErr);
    if (nErr || uid.length == 0 || token.length == 0) {
        NSLog(@"-----------------------> UserLogin errorMassage:%@", errorMessage);
    } else {
        NSLog(@"-----------------------> UserLogin uid:%@ token:%@", uid, token);
        self.uid = uid;
        self.token = token;
    }

}

-(NSString*) wifiName {
    if(_wifiName == nil) {
        NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
        NSDictionary *info = nil;
        for (NSString *ifnam in ifs) {
            info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
            if (info && [info count]) {
                break;
            }
        }
        _wifiName = [info objectForKey:@"SSID"];
    }
    return _wifiName;
}

/**
 配置设备连接路由的方法
 @param ssid 需要配置到路由的SSID名
 @param key 需要配置到路由的密码
 @param mode 配置方式
 @see XPGConfigureMode
 @param softAPSSIDPrefix SoftAPMode模式下SoftAP的SSID前缀或全名（XPGWifiSDK以此判断手机当前是否连上了SoftAP，AirLink配置时该参数无意义，传nil即可）
 @param timeout 配置的超时时间 SDK默认执行的最小超时时间为30秒
 @param types 配置的wifi模组类型列表，存放NSNumber对象，SDK默认同时发送庆科和汉枫模组配置包；SoftAPMode模式下该参数无意义。types为nil，SDK按照默认处理。如果只想配置庆科模组，types中请加入@XPGWifiGAgentTypeMXCHIP类；如果只想配置汉枫模组，types中请加入@XPGWifiGAgentTypeHF；如果希望多种模组配置包同时传，可以把对应类型都加入到types中。XPGWifiGAgentType枚举类型定义SDK支持的所有模组类型。
 @see 对应的回调接口：[XPGWifiSDKDelegate XPGWifiSDK:didSetDeviceWifi:result:]

- (void)setDeviceWifi:(NSString*)ssid
                  key:(NSString*)key
                 mode:(XPGConfigureMode)mode
     softAPSSIDPrefix:(NSString*)softAPSSIDPrefix
              timeout:(int)timeout
       wifiGAgentType:(NSArray*)types;
 
 
 */
-(int) startConfig: (id<UMAsyncJobDelegate>)JobDelegate {
    //XPGWifiGAgentTypeESP = 4
    [[XPGWifiSDK sharedInstance] setDeviceWifi:self.wifiName key:self.wifiPwd mode:XPGWifiSDKAirLinkMode softAPSSIDPrefix:nil timeout:XPG_AIRLINK_TIMEOUT wifiGAgentType:@[@4]];
    return BindDeviceJobId;
}

- (void)XPGWifiSDK:(XPGWifiSDK *)wifiSDK didSetDeviceWifi:(XPGWifiDevice *)device result:(int)result
{
    // XPGWifiError_CONFIGURE_TIMEOUT：配置超时
    if(result == 0)
    {
        NSLog(@"配置成功");
    }
    else
    {
        NSLog(@"配置失败");
    }
}

-(int) getBindedDevice:(id<UMAsyncJobDelegate>)JobDelegate {
    if(deviceDelegate == nil) {
        deviceDelegate = [NSMutableArray new];
    }
    [deviceDelegate addObject:JobDelegate];
    
    [[XPGWifiSDK sharedInstance] getBoundDevicesWithUid:self.uid token:self.token specialProductKeys:self.productkey, nil];
    return GetDeviceJobId;
}

- (void)XPGWifiSDK:(XPGWifiSDK *)wifiSDK didDiscovered:(NSArray *)deviceList result:(int)result
{
    for(id<UMAsyncJobDelegate> dv in deviceDelegate) {
        if ([dv respondsToSelector:@selector(UMAsyncJobDone:JobCookie:And:)]) {
            [dv UMAsyncJobDone:result==0 JobCookie:GetDeviceJobId And:deviceList];
        }
    }
    [deviceDelegate removeAllObjects];
}

@end
